package thread.java20221219;

/**
 * 多线程的优势
 */
public class Demo17 {
//    private static long count = 10_0000_0000;
    private static long count = 1000;

    public static void main(String[] args) throws InterruptedException {
        single();
        multi();
    }

    /**
     * 多线程
     */
    private static void multi() throws InterruptedException {
        long start = System.currentTimeMillis();
        Thread t1 = new Thread(()->{
            long a = 0;
            for (long i= 0;i<count;i++){
                a++;
            }
        });
        t1.start();
        Thread t2 = new Thread(()->{
            long b = 0;
            for (long i= 0;i<count;i++){
                b++;
            }
        });
        t2.start();
        //TODO
        //此处不可以就这样记录结束时间
        //这个记录时间是在main线程里面执行的, main线程和t1 t2 是并发执行, 那么此时, t1和t2还没执行完呢
        //应该等待t1 和t2 执行完毕, 才可以打印时间
        //t1.join  main线程要等待t1 执行完了, 才可以, t2.join() main线程要等待t2执行完了
        t1.join();
        t2.join();
        long end = System.currentTimeMillis();
        System.out.println("多线程消耗时间:" + (end-start) + "ms");
    }

    /**
     * 单线程
     */
    private static void single() {
        long start = System.currentTimeMillis();
        long a =0;
        long b = 0;
        for (long i=0;i<count;i++){
            a++;
        }
        for (long i=0;i<count;i++){
            b++;
        }
        long end = System.currentTimeMillis();
        System.out.println("单线程的消耗时间:" + (end-start) +"ms");
    }
}
